package com.weigang.webservice.interceptor;

import com.weigang.webservice.utils.Constant;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.util.List;

public class ClientLoginInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
    private String username;
    private String password;

    public ClientLoginInterceptor(String username, String password) {
        super("pre-protocol");
        this.username = username;
        this.password = password;
    }

    public void handleMessage(SoapMessage message) throws Fault {
        List<Header> headers = message.getHeaders();
        // 第一步：初始化一个XML解析工厂。
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        Document document = builder.newDocument();
        Element rootElement = document.createElement("login");
        rootElement.setAttribute("xmlns", Constant.NAMESPACE);
        Element usernameElement = document.createElement("username");
        usernameElement.setTextContent(this.username);
        rootElement.appendChild(usernameElement);
        Element passwordElement = document.createElement("password");
        passwordElement.setTextContent(this.password);
        rootElement.appendChild(passwordElement);
        headers.add(new Header(new QName("login"), rootElement));
        System.out.println("拦截...");
    }
}
